﻿<%@ WebHandler Language="C#" Class="ApsEmployeeArrangeHandler" %>

//Description:手动排班类
//Copyright (c) : 通力凯顿（北京）系统集成有限公司
//Writer:yuxj
//create Date:2023.4.1
using System;
using System.Web;
using BusinessRule.DTO;
using BusinessRule.Business;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Web.SessionState;
using System.Data;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using DatabaseAccess.DBUtility;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;

public class ApsEmployeeArrangeHandler : IHttpHandler, IRequiresSessionState
{   
    private uLMSCommonIBusiness m_CommonObj = uMESBusinessFactory.instance.GetuLMSCommonObject();
    string fileBasePath = System.Configuration.ConfigurationManager.AppSettings["ImportPath"].ToString();//导入临时路径
    private EmployeeMaintPageBusiness m_EmpMaint = new EmployeeMaintPageBusiness();
    CurrentUserInfo m_UserInfo;
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            var action = context.Request["action"].ToString();           
            switch (action)
            {
                case "searchData": //查询汇总
                    ApsEmployeeWorkSum(context);
                    break;
                case "searchApsEmployeeWorkDetail"://查询明细
                    ApsEmployeeWorkDetail(context);
                    break;
                case "apsEmployeeWorkDateImport"://信息导入
                    EmployeeWorkDateImport(context);
                    break;
                case "apsWorkShiftModelExport"://模板导出
                    EmployeeWorkDateModelExport(context);
                    break;
                case "getWorkShift"://查询班次
                    ApsWorkShift(context);
                    break;
                case "saveWorkShift"://保存班次
                    SaveWorkShift(context);
                    break;
                case "getFactory":
                    GetFactory(context);
                    break;     
                default:
                    break;
            }
        }
        catch (Exception e)
        {
            var result = new uMESProcessResult()
            {
                Result = false,
                Message = e.Message
            };
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

    private Dictionary<string, string> GetPara(HttpContext context)
    {
        Dictionary<string, string> para = new Dictionary<string, string>();

        para.Add("CurrentPageIndex", context.Request.Form["pageNumber"].ToString());//页码
        para.Add("PageSize", context.Request.Form["pageSize"].ToString());//每页页数

        if (!string.IsNullOrWhiteSpace(context.Request.Form["factoryId"]))
        {
            para.Add("FactoryId", context.Request.Form["factoryId"].ToString());
        }
        
        if (!string.IsNullOrWhiteSpace(context.Request.Form["workCenterId"]))
        {
            para.Add("WorkCenterId", context.Request.Form["workCenterId"]);
        }

        if (!string.IsNullOrWhiteSpace(context.Request.Form["teamId"]))
        {
            para.Add("TeamId", context.Request.Form["teamId"].ToString());
        }

        if (!string.IsNullOrWhiteSpace(context.Request.Form["employeeName"]))
        {
            para.Add("EmployeeName", context.Request.Form["employeeName"].ToString());
        }

        if (!string.IsNullOrWhiteSpace(context.Request.Form["fullName"]))
        {
            para.Add("FullName", context.Request.Form["fullName"].ToString());
        }

        //前台验证了日期必选
        if (!string.IsNullOrWhiteSpace(context.Request.Form["startDate"]))
        {
            para.Add("StartDate", context.Request.Form["startDate"].ToString());
        }
        if (!string.IsNullOrWhiteSpace(context.Request.Form["startDate"]))
        {
            para.Add("EndDate", context.Request.Form["endDate"].ToString());
        }
        
        
        return para; 
    }            
    /// <summary>
    /// 查询获取汇总数据列表
    /// </summary>
    /// <param name="context"></param>
    public void ApsEmployeeWorkSum(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        uMESProcessResult result = new uMESProcessResult();
        result.Result = false;
        Dictionary<string, string> para = GetPara(context);        
        result = m_EmpMaint.GetEmpWkShiftSumInfo(para,false);        
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 查询获取明细数据列表
    /// </summary>
    /// <param name="context"></param>
    public void ApsEmployeeWorkDetail(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        uMESProcessResult result = new uMESProcessResult();
        result.Result = false;
        Dictionary<string, string> para = GetPara(context);
        result = m_EmpMaint.GetEmpWkShiftDetail(para, true);        
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 查询班次列表
    /// </summary>
    /// <param name="context"></param>
    public void ApsWorkShift(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        uMESProcessResult result = new uMESProcessResult();
        result.Result = true;
        result.DBTable = GetWorkShift("");       
        result.Message = "";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    
    /// <summary>
    /// 更新班次信息
    /// </summary>
    /// <param name="context"></param>
    public uMESProcessResult SaveWorkShift(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        uMESProcessResult result = new uMESProcessResult();
        Dictionary<string, string> para = new Dictionary<string, string>();
        if (context.Request["workshiftid"] != null) //&& !string.IsNullOrWhiteSpace(context.Request["workshiftid"])
        {//班次            
            para.Add("workshiftid", context.Request["workshiftid"].ToString());
        }

        if (context.Request["employeename"] != null && !string.IsNullOrWhiteSpace(context.Request["employeename"]))
        {//人员            
            para.Add("employeename", context.Request["employeename"].ToString());
        }

        if (context.Request["workdate"] != null && !string.IsNullOrWhiteSpace(context.Request["workdate"]))
        {//日期            
            para.Add("workdate", context.Request["workdate"].ToString());
        }

        result.Result = m_EmpMaint.SaveWorkShift(para);
        result.Message = "";
        context.Response.Write(JsonConvert.SerializeObject(result));
        return result;
    }

    /// <summary>
    /// 获取车间
    /// </summary>
    /// <param name="context"></param>
    public void GetFactory(HttpContext context)
    {
        DataTable dt = m_CommonObj.GetFactory(new Dictionary<string, string>());
        DataTable result = new DataTable();
        result.Columns.Add("FACTORYID");
        result.Columns.Add("FACTORYNAME");

        //无分厂时填充一行空值
        DataRow reRow = result.NewRow();
        reRow["FACTORYID"] = m_UserInfo.FactoryID;
        reRow["FACTORYNAME"] = m_UserInfo.Factory;
        result.Rows.Add(reRow);

        //如果登陆人包含分厂，只能看到本分厂的，无分厂时可以看全部
        if (m_UserInfo.FactoryID == "") 
        {
            foreach (DataRow row in dt.Rows)
            {
                if (row["FACTORYID"].ToString() == m_UserInfo.FactoryID)
                {
                    continue;
                }
                reRow = result.NewRow();
                reRow["FACTORYID"] = row["FACTORYID"];
                reRow["FACTORYNAME"] = row["FACTORYNAME"];

                result.Rows.Add(reRow);
            }
        }
        result.AcceptChanges();
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    public void EmployeeWorkDateImport(HttpContext context)
    {
        string fpath = string.Empty;
        try
        {
            var files = context.Request.Files;
            if (files.Count == 0)
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "未上传文件！", Result = false }));
                return;
            }

            if (!System.IO.Directory.Exists(context.Server.MapPath(fileBasePath)))
            {
                System.IO.Directory.CreateDirectory(context.Server.MapPath(fileBasePath));
            }
            var file = files.Count > 1 ? files[files.Count - 1] : files[0];
            string IsXls = System.IO.Path.GetExtension(file.FileName);
            string fileName = System.IO.Path.GetFileNameWithoutExtension(file.FileName) + DateTime.Now.ToString("yyyyMMddHHmmssffff") + IsXls;
            fpath = context.Server.MapPath(fileBasePath + fileName);
            file.SaveAs(fpath);//保存文件，处理完成后删除
            NPOI.SS.UserModel.IWorkbook Workbook = uLMS_CommonFunction.GetWorkbookObj(fpath);
            DataTable dt = uLMS_CommonFunction.ExcelImportToDataTable(Workbook);
            uLMS_CommonFunction.DeleteFile(fpath);
            uMESProcessResult result = SaveData(dt);
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
        catch (Exception ex)
        {
            uLMS_CommonFunction.DeleteFile(fpath);//报错，则删除上传的文件
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = ex.Message, Result = false }));
        }
    }

    /// <summary>
    /// 新的模板 年份	月份	员工号	人员姓名 1,2,3,4....（本月日期）
    /// </summary>
    /// <param name="dt"></param>
    /// <returns></returns>
    private uMESProcessResult SaveData(DataTable dt)
    {
        DataTable Rightdt = new DataTable();//格式正确行数据集 
        Rightdt.Columns.Add("employeeid");
        Rightdt.Columns.Add("fullname");
        Rightdt.Columns.Add("workshiftid");
        Rightdt.Columns.Add("workdate");

        DataTable Errordt = new DataTable();//格式错误行数据集    
        Errordt.Columns.Add("Error");
        uMESProcessResult result = new uMESProcessResult();
        var heardStr = string.Empty;
        if (!dt.Columns.Contains("员工号"))
        {
            heardStr += "【员工号】列，";
        }
        if (!dt.Columns.Contains("人员姓名"))
        {
            heardStr += "【人员姓名】列，";
        }
        if (!dt.Columns.Contains("年份"))
        {
            heardStr += "【年份】列，";
        }
        if (!dt.Columns.Contains("月份"))
        {
            heardStr += "【月份】列，";
        }
        if (!string.IsNullOrWhiteSpace(heardStr))
        {
            result.Message = "Excle 中未包含" + heardStr.TrimEnd(',') + "数据";
            result.Result = false;
            return result;
        }

        DataTable dtTemp = new DataTable();//临时datatable
        //判断班次是否存在
        DataView dv;
        DataTable dtWorkShift = new DataTable();
        dtWorkShift.Columns.Add("workshiftname");
        for (int j = 1; j <= 31; j++)
        {
            if (dt.Columns.Contains(j.ToString()))
            {
                dv = dt.DefaultView;
                foreach (DataRow dr in dv.ToTable(true, j.ToString()).Rows)
                {
                    dtWorkShift.Rows.Add(dr[0]);
                }                
            }
        }
        //增加清空逻辑 没有班次时执行清除-如下需注释
        //if ((dtWorkShift.Rows.Count == 0) || (dtWorkShift.Select("workshiftname is not null and workshiftname<>''").Length == 0))
        //{
        //    result.Message = "Excle 中未包含有效的班次数据";
        //    result.Result = false;
        //    return result;
        //}
        
        dtWorkShift = dtWorkShift.DefaultView.ToTable(true);
        //dtWorkShift = dtWorkShift.Select("workshiftname is not null and workshiftname<>''").CopyToDataTable();
        if (!dtWorkShift.Columns.Contains("WORKSHIFTID"))
        {
            dtWorkShift.Columns.Add("workshiftid");
        }
        foreach (DataRow drWorkShift in dtWorkShift.Rows)
        {
            string tempWorkShiftName = drWorkShift["workshiftname"].ToString();
            dtTemp = GetWorkShift(tempWorkShiftName);
            if (!string.IsNullOrWhiteSpace(tempWorkShiftName))
            {
                if (dtTemp.Rows.Count > 0)
                {
                    drWorkShift["workshiftId"] = dtTemp.Rows[0]["workshiftid"].ToString();
                }
                else
                {
                    //班次不存在,直接退出
                    result.Message = "班次：" + drWorkShift["workshiftname"].ToString() + " 不存在";
                    result.Result = false;
                    return result;
                }
            }
        }
        
        
        //获取年份,月份 判断是否为闰年 及是否为2月份
        //闰年2月取29 平年2月取28 其他按照大月31 小月30天取
        //判断员工号，人员姓名正确 判断班次存储
        var k = 2; //错误行号   
        string employeeId = "";
        string employeename = "";
        string fullName = "";
        string workshiftId = "";
        string workdate = "";
        foreach (DataRow row in dt.Rows)
        {
            int Month = 0;
            int Year = 0;
            bool boolLeapYear=false;
            var errStr = string.Empty;
            if (string.IsNullOrWhiteSpace(row["人员姓名"].ToString()))
            {
                errStr += "人员姓名：【" + row["人员姓名"].ToString() + "】为空,";
            }
            else
                fullName = row["人员姓名"].ToString();

            if (string.IsNullOrWhiteSpace(row["员工号"].ToString()))
            {
                errStr += "员工号：【" + row["员工号"].ToString() + "】为空,";
            }
            else
                employeename = row["员工号"].ToString();

            if (string.IsNullOrWhiteSpace(row["年份"].ToString()))
            {
                errStr += "年份：【" + row["年份"].ToString() + "】为空,";
            }
            else
            {                
                if (int.TryParse(row["年份"].ToString(), out Year))
                {
                    boolLeapYear = isLeapYear(Year);
                }
                else
                    errStr += "年份：【" + row["年份"].ToString() + "】不为数字,";                
            }

            if (string.IsNullOrWhiteSpace(row["月份"].ToString()))
            {
                errStr += "月份：【" + row["月份"].ToString() + "】为空,";
            }
            else
            {                
                if (!int.TryParse(row["月份"].ToString(), out Month))
                {
                    errStr += "月份：【" + row["月份"].ToString() + "】不为数字,";
                }
            }

            //增加分厂判断 本分厂人员只能导入本分厂的数据
            string factoryid = m_UserInfo.FactoryID;
            employeeId = GetEmployeeId(fullName,employeename);
            if (string.IsNullOrWhiteSpace(employeeId))
            {
                errStr += "人员姓名:【" + row["人员姓名"].ToString() + "】 ,员工号:【" + row["员工号"].ToString() + "】不匹配,";
            }
            else if (factoryid!="")
            {
                if (factoryid != GetEmpFactoryId(employeeId))
                {
                    errStr += "人员姓名:【" + row["人员姓名"].ToString() + "】 ,员工号:【" + row["员工号"].ToString() + "】与登录人分厂不匹配,";
                }
            }        

            if (!string.IsNullOrWhiteSpace(errStr))
            {
                //result.Message = errStr;
                //result.Result = false;
                //return result;
                DataRow ERow = Errordt.NewRow();
                ERow["Error"] = "第" + k + "行：" + errStr.TrimEnd(',');
                Errordt.Rows.Add(ERow);
            }

            string workshiftName = "";
            for (int i = 1; i <= 31; i++)
            {
                //多余的列不计算，空班次列不计算 已经报错的列不计算----->改为空班次列执行删除计算 && (!string.IsNullOrWhiteSpace(row[i.ToString()].ToString())
                if (dt.Columns.Contains(i.ToString())  && string.IsNullOrWhiteSpace(errStr))
                {
                    workshiftName = row[i.ToString()].ToString();
                    if (Month == 2)
                    {
                        if (isLeapYear(Year))
                        {
                            if (i >= 30) continue;
                        }
                        else
                        {
                            if (i >= 29) continue;                             
                        }

                    }
                    else if ((Month == 1) || (Month == 3) || (Month == 5) || (Month == 7) || (Month == 8) || (Month == 10) || (Month == 12))
                    {
                        //大月
                    }
                    else
                    {
                        if (i >= 31) continue;  //小月
                    }
                    if (workshiftName != "")
                    {
                        workshiftId = dtWorkShift.Select(string.Format("workshiftname='{0}'", workshiftName))[0]["workshiftid"].ToString();
                    }
                    else
                        workshiftId = "";
                    workdate=Year.ToString()+"-"+Month+"-"+i.ToString();
                    Rightdt.Rows.Add(employeeId, fullName, workshiftId, workdate);
                }
            }

            k++;  
        }

        if (Rightdt.Rows.Count > 0)
        {
            result.Result = m_EmpMaint.EmployeeWorkDateImport(Rightdt);
            result.Message = result.Result ? "导入成功" + Rightdt.Rows.Count + "条数据" + (Errordt.Rows.Count > 0 ? ";导入失败" + Errordt.Rows.Count + "条数据" : "") : "导入失败";
        }
        else
        {
            result.Result = false;
            result.Message = "导入失败，没有数据导入";
        }


        result.ReturnData = Errordt;
        return result;
        
        
    }

    /// <summary>
    /// 判断是否为闰年 能被400整除是闰年，能被4整除不能被100整除的是闰年
    /// </summary>
    /// <param name="Year"></param>
    /// <returns></returns>
    private bool isLeapYear(int Year)
    {
        if (Year % 400 == 0) return true;
        if ((Year % 4 == 0) && (Year % 100 != 0)) return true;
        return false;
    }
    
    /// <summary>
    /// 处理Excle单元格数据-->旧的模板(员工号，人员姓名，日期，班次)
    /// </summary>
    /// <param name="sheet"></param>
    /// <param name="IsXls"></param>
    /// <returns></returns>
    private uMESProcessResult SaveDataOld(DataTable dt)
    {
        DataTable Rightdt = new DataTable();//格式正确行数据集 
        Rightdt.Columns.Add("employeeid");
        Rightdt.Columns.Add("fullname");
        Rightdt.Columns.Add("workshiftid");
        Rightdt.Columns.Add("workdate");
                
        DataTable Errordt = new DataTable();//格式错误行数据集    
        Errordt.Columns.Add("Error");              
        uMESProcessResult result = new uMESProcessResult();
        var heardStr = string.Empty;
        if (!dt.Columns.Contains("员工号"))
        {
            heardStr += "【员工号】列，";
        }
        if (!dt.Columns.Contains("人员姓名"))
        {
            heardStr += "【人员姓名】列，";
        }
        if (!dt.Columns.Contains("日期"))
        {
            heardStr += "【日期】列，";
        }
        if (!dt.Columns.Contains("班次"))
        {
            heardStr += "【班次】列，";
        }        
        if (!string.IsNullOrWhiteSpace(heardStr))
        {
            result.Message = "Excle 中未包含" + heardStr.TrimEnd(',') + "数据";
            result.Result = false;
            return result;
        }
        
        var i = 2;         
        DataTable dtTemp = new DataTable();
        string employeeId = "";
        string fullName="";
        string workshiftId = "";        
        string workdate = "";
        
        DateTime tempWorkDate=new DateTime();
        foreach (DataRow row in dt.Rows)
        {            
            var errStr = string.Empty;           
            if (string.IsNullOrWhiteSpace(row["人员姓名"].ToString()))
            {
                errStr += "人员姓名：【" + row["人员姓名"].ToString() + "】为空,";                 
            }
            fullName=row["人员姓名"].ToString();
            
            if (string.IsNullOrWhiteSpace(row["员工号"].ToString()))
            {
                errStr += "员工号：【" + row["员工号"].ToString() + "】为空,";                 
            }
            if (string.IsNullOrWhiteSpace(row["班次"].ToString()))
            {
                errStr += "班次：【" + row["班次"].ToString() + "】为空,";       
            }
            if (string.IsNullOrWhiteSpace(row["日期"].ToString()))
            {
                errStr += "日期：【" + row["日期"].ToString() + "】为空,";
            }
            else
            {
                if (DateTime.TryParse(row["日期"].ToString(), out tempWorkDate))
                {
                    //日期格式
                    workdate = tempWorkDate.ToShortDateString();
                }
                else
                    errStr += "日期：【" + row["日期"].ToString() + "】格式不正确(应为年月日格式:yyyy-MM-dd 或yyyy/MM/dd),";
            }            
            
            if (string.IsNullOrWhiteSpace(errStr))
            {
                employeeId = GetEmployeeId(row["人员姓名"].ToString(), row["员工号"].ToString());
                if (string.IsNullOrWhiteSpace(employeeId))
                {
                    errStr += "人员姓名:【" + row["人员姓名"].ToString() + "】 ,员工号:【" + row["员工号"].ToString() + "】不匹配,";
                }
                dtTemp=GetWorkShift(row["班次"].ToString());
                if(dtTemp.Rows.Count>0)
                {
                    workshiftId = dtTemp.Rows[0]["workshiftid"].ToString();
                }
                if (string.IsNullOrWhiteSpace(workshiftId))
                {
                    errStr += " 班次:【" + row["班次"].ToString() + "】不存在,";
                }
            }

            if (!string.IsNullOrWhiteSpace(errStr))
            {
                DataRow ERow = Errordt.NewRow();
                ERow["Error"] = "第" + i + "行：" + errStr.TrimEnd(',');
                Errordt.Rows.Add(ERow);
            }
            else
            {
                Rightdt.Rows.Add(employeeId, fullName, workshiftId, workdate);
            }
                        
            i++;
        }

        if (Rightdt.Rows.Count > 0)
        {
            result.Result = m_EmpMaint.EmployeeWorkDateImport(Rightdt);
            result.Message = result.Result ? "导入成功" + Rightdt.Rows.Count + "条数据" + (Errordt.Rows.Count > 0 ? ";导入失败" + Errordt.Rows.Count + "条数据" : "") : "导入失败";
        }
        else
        {
            result.Result = false;
            result.Message = "导入失败，没有数据导入";
        }
        
            
        result.ReturnData = Errordt;
        return result;
    }

    
    /// <summary>
    /// 人员
    /// </summary>
    /// <param name="fullname"></param>
    /// <param name="employeename"></param>
    /// <returns></returns>
    private string GetEmployeeId(string fullname, string employeename)
    {
        string sql = "select employeeid from employee e where e.fullname='{0}' and e.employeename='{1}'";
        DataTable dt = DatabaseHelper.Query_ReturnDatTable(string.Format(sql, fullname,employeename));
        if (dt.Rows.Count > 0)
            return dt.Rows[0]["employeeid"].ToString();
        else
            return "";
    }

   /// <summary>
    /// 班次
   /// </summary>
   /// <returns></returns>
    private DataTable GetWorkShift(string workshiftname)
    {
        string sql = "select workshiftid,workshiftname from workshift where 1=1 ";
        if (workshiftname != "")
        {
            sql += string.Format(" and workshiftname='{0}' ", workshiftname);
        }
        sql += " order by workshiftname ";
        DataTable dt = DatabaseHelper.Query_ReturnDatTable(string.Format(sql, workshiftname));
        if (workshiftname == "") //如果为全查，用于给下拉列表赋值
        {
            dt.Rows.Add("空", "空");//增加空列
        }
        return dt;
    }

    /// <summary>
    /// 厂别
    /// </summary>
    /// <returns></returns>
    private string GetEmpFactoryId(string employeeId)
    {
        string sql = string.Format("select sv.factoryid from employee e left join sessionvalues sv on e.sessionvaluesid=sv.sessionvaluesid where e.employeeid='{0}' ", employeeId);        
        DataTable dt = DatabaseHelper.Query_ReturnDatTable(sql);
        return dt.Rows[0]["factoryid"].ToString();
    }

    /// <summary>
    /// 导入模板导出
    /// </summary>
    /// <param name="context"></param>
    public void EmployeeWorkDateModelExport(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        uMESProcessResult result = new uMESProcessResult();
        result.Result = false;

        DataTable dt = new DataTable();
        //构造模板列表
        dt.Columns.Add("年份");
        dt.Columns.Add("月份");
        dt.Columns.Add("员工号");
        dt.Columns.Add("人员姓名");
              
        for (int i = 1; i <= 31; i++)
        {
            dt.Columns.Add(i.ToString());            
        }
        for (int j = 0; j < 2; j++)
        {
            DataRow dr = dt.NewRow();
            dr["年份"] = DateTime.Now.Year;
            dr["月份"] = DateTime.Now.AddMonths(j).Month;
            dr["员工号"] = m_UserInfo.EmployeeName;
            dr["人员姓名"] = m_UserInfo.FullName;
            for (int i = 1; i <= 31; i++)
            {
                dr[i.ToString()]="白班";
            }
            dt.Rows.Add(dr);
        }
        var ms = uLMS_CommonFunction.DataTableExportToExcel(dt, "排班模板（导入时删掉本行）");
        var Response = HttpContext.Current.Response;
        Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}{1}.xls", HttpContext.Current.Server.UrlEncode("排班模板"), DateTime.Now.ToString("yyyy-MM-dd-HH:mm:ss")));
        Response.AddHeader("fileDownload", "1");
        Response.AddHeader("Set-Cookie", "fileDownload=true;path=/");
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
        Response.ContentType = "application/ms-excel;charset=UTF-8";
        Response.BinaryWrite(ms);

        Response.Flush();
        Response.End();
        Response.Close();

        context.Response.Write(JsonConvert.SerializeObject(Response));
    }
    ///// <summary>
    ///// 排产结果调整导入
    ///// </summary>
    ///// <param name="context"></param>
    //private void EmployeeWorkDateImport(HttpContext context)
    //{
    //    string fpath = string.Empty;
    //    try
    //    {
    //        var files = context.Request.Files;
    //        if (files.Count == 0)
    //        {
    //            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "未上传文件！", Result = false }));
    //            return;
    //        }

    //        if (!System.IO.Directory.Exists(context.Server.MapPath(fileBasePath)))
    //        {
    //            System.IO.Directory.CreateDirectory(context.Server.MapPath(fileBasePath));
    //        }
    //        var file = files.Count > 1 ? files[files.Count - 1] : files[0];
    //        string IsXls = System.IO.Path.GetExtension(file.FileName);
    //        string fileName = System.IO.Path.GetFileNameWithoutExtension(file.FileName) + DateTime.Now.ToString("yyyyMMddHHmmssffff") + IsXls;
    //        fpath = context.Server.MapPath(fileBasePath + fileName);
    //        file.SaveAs(fpath);//保存文件，处理完成后删除
    //        IWorkbook Workbook = uLMS_CommonFunction.GetWorkbookObj(fpath);
    //        if (Workbook == null)
    //        {
    //            DeleteFile(fpath);
    //            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "解析出错", Result = false }));
    //            return;
    //        }
    //        DeleteFile(fpath);
    //        ISheet sheet = Workbook.GetSheetAt(0);

    //        var dt = uLMS_CommonFunction.ExcelImportToDataTable(Workbook, 1);

    //        uMESProcessResult result;
    //        result = GetapsLmCalculateData(dt);
    //        context.Response.Write(JsonConvert.SerializeObject(result));
    //    }
    //    catch (Exception ex)
    //    {
    //        DeleteFile(fpath);//报错，则删除上传的文件
    //        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = ex.Message, Result = false }));
    //    }
    //}

    ///// <summary>
    ///// 删除文件
    ///// </summary>
    ///// <param name="fpath">文件地址</param>
    //private void DeleteFile(string fpath)
    //{
    //    if (File.Exists(fpath))
    //    {
    //        new FileInfo(fpath).Attributes = FileAttributes.Normal;
    //        File.Delete(fpath);
    //    }
    //}

    ///// <summary>
    ///// 获取单元格值
    ///// </summary>
    ///// <param name="cell"></param>
    ///// <returns></returns>
    //private string GetCellValue(ICell cell)
    //{
    //    try
    //    {
    //        if (cell == null)
    //        {
    //            return "";
    //        }
    //        if (cell.CellType == CellType.Formula)//判断单元格是否有公式
    //        {
    //            cell.SetCellType(CellType.String);
    //        }
    //        if (cell.CellType == CellType.Numeric)//
    //        {
    //            if (DateUtil.IsCellDateFormatted(cell))
    //            {//判断单元是日期格式，特殊处理
    //                var c = DateTime.FromOADate(cell.NumericCellValue);
    //                return c.ToString("yyyy/MM/dd HH:mm:ss");
    //            }
    //        }
    //        return cell.ToString().Trim();
    //    }
    //    catch (Exception e)
    //    {
    //        return "";
    //    }
    //}

}